import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
import filter from './filter/filter'
import Tool from '../public/static/js/tool'
import Toast from '../public/static/js/toast'
import Loading from '../public/static/js/loading'
import Confirm from '../public/static/js/confirm'
import '../public/static/js/session-storage'


Vue.config.productionTip = false
Vue.prototype.$axios = axios;
// 携带cookie，并且可用于保证sessionId一致
axios.defaults.withCredentials = true
axios.defaults.timeout = 60000;

/** 登录拦截 */
axios.interceptors.request.use(config => {
  let token = SessionStorage.get(SESSION_KEY_USER).token
  if (Tool.isNotEmpty(token)) {
    config.headers.token = token
  }
  return config
}, (err) => {
  Loading.hide()
  Toast.error("请求异常")
  return Promise.reject(err)
})
axios.interceptors.response.use(response => {
  if (response.data.code == 401) {
    router.push('/login')
  } else {
    return response
  }
}, (err) => {
  Loading.hide()
  let status = err.response.status
  if (err.message.includes('timeout')) {   // 判断请求异常信息中是否含有超时timeout字符串
    Toast.error('请求超时');
  } else if (status == 503) {
    Toast.error('网关错误');
  } else if (status == 500) {
    Toast.error('系统错误');
  } else if (status == 400) {
    Toast.error('请求参数错误');
  } else if (status == 404) {
    Toast.error('资源不存在');
  } else {
    Toast.error('未知错误');
  }
  return Promise.reject(err)
})

router.beforeEach((to, from, next) => {
  // 对 loginRequire 属性做监控拦截
  if (to.matched.some(item => {
    return item.meta.loginRequire
  })) { // if块
    let loginUser = SessionStorage.get(SESSION_KEY_USER)
    if (Tool.isEmpty(loginUser)) {
      next('/login') // session中没有用户信息，跳转登录页面
    } else {
      next() // 放行
    }
  } else {
    next() // 未设置监控拦截，直接放行
  }
})

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

Object.keys(filter).forEach(key => {
  Vue.filter(key, filter[key])
})